import router from './router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth'
import store from '@/store'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()
  const hasToken = getToken()
  if (hasToken) {
    // 有token
    if (to.path === '/login') {
      // 中转到主页跳转到主页
      // next地址后 之前并没有执行后置守卫，需要手动将进度条关闭
      next({ path: '/' })
      NProgress.done()
    } else {
      // console.log(store.getters.userId)
      // get user info、
      if (!store.getters.userId) {
        await store.dispatch('user/getUserInfo')
      }
      next() // 放过
    }
  } else {
    // 无token
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  // console.info('finish progress bar')
  NProgress.done()
})
